package com.sh.rbac.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.rbac.core.common.constant.CacheConstants;
import com.sh.rbac.domain.dto.user.UserQueryDTO;
import com.sh.rbac.domain.entity.User;
import com.sh.rbac.service.OnlineUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author wb
 * @since 2025-10-13
 */

@Service
public class OnlineUserServiceImpl implements OnlineUserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Page<User> getPage(Long current, Long limit, UserQueryDTO userQueryDTO) {
        Page<User> page = new Page<>(current, limit);

        // 获取所有用户
        List<User> users = getAll();

        // 条件过滤
        String username = userQueryDTO.getUsername();
        if (username != null) {
            users.removeIf(u -> !u.getUsername().contains(username));
        }

        // 计算分页
        int fromIndex = ((current.intValue() - 1) * limit.intValue());
        int toIndex = Math.min(fromIndex + limit.intValue(), users.size());
        List<User> pageRecords = fromIndex < users.size() ?
                users.subList(fromIndex, toIndex) : new ArrayList<>();

        page.setRecords(pageRecords);
        page.setTotal(users.size());

        return page;
    }

    @Override
    public List<User> getAll() {
        List<User> users = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(CacheConstants.LOGIN_USER_KEY + "*");
        if (keys != null) {
            keys.forEach(token -> {
                Object obj = redisTemplate.opsForValue().get(token);
                if (obj == null) {
                    return;
                }
                if (obj instanceof User u) {
                    // 判断是否过期
                    if (u.getExpiration() < System.currentTimeMillis()) {
                        return;
                    }
                    users.add(u);
                }
            });
        }
        return users;
    }

    @Override
    public Boolean quitUser(String token) {
        return redisTemplate.delete(CacheConstants.LOGIN_USER_KEY + token);
    }
}
